import Dialog from 'tdesign-miniprogram/dialog/index';
import Message from 'tdesign-miniprogram/message/index';

import userStore from '@/store/user';
import intervalStore from '@/store/interval';
import { createStoreBindings } from '@/miniprogram_npm/mobx-miniprogram-bindings/index';

import { resetStore } from '@/utils/store';
import { updateUser, updateUseravatar, getValidateCode, checkValidateCode } from '@/service/api/user';

const dialogDefaultConfig = (context, title, content, selector) => {
    return {
        context: context,
        selector: selector ?? '#t-dialog',
        title: title ?? null,
        content: content ?? null,
        confirmBtn: '确定',
        cancelBtn: '取消'
    };
};

const messageDefaultConfig = (content) => {
    return {
        context: this,
        offset: [60, 32],
        content: content
    };
};

let validateChecked = false;

const passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;

Page({
    data: {
        currentGuide: 0,
        guideSteps: [],
        usernameDialogVisible: false,
        passwordDialogVisible: false,
        emailDialogVisible: false,
        newUsername: '',
        newPassword: '',
        newEmail: '',
        validateCode: ''
    },

    onLoad() {
        this.intervalStoreBindings = createStoreBindings(this, {
            store: intervalStore,
            fields: ['currentSecond'],
            actions: ['setNewInterval']
        });
        this.userStoreBingdings = createStoreBindings(this, {
            store: userStore,
            fields: ['userInfo'],
            actions: ['updateUserInfo', 'getUserInfo']
        });
        if (!wx.getStorageSync('guide-finish')) {
            this.setData({
                guideSteps: [
                    {
                        element: () =>
                            new Promise((resolve) =>
                                this.createSelectorQuery()
                                    .select('#editable-cell')
                                    .boundingClientRect((rect) => resolve(rect))
                                    .exec()
                            ),
                        title: '操作指引',
                        body: '右滑可以编辑个人信息',
                        placement: 'center'
                    }
                ]
            });
        }
    },

    onUnload() {
        this.intervalStoreBindings.destroyStoreBindings();
        this.userStoreBingdings.destroyStoreBindings();
    },

    logout: () => {
        // 清除全局状态管理
        resetStore();
        // 清除小程序缓存
        wx.clearStorage();
        wx.reLaunch({
            url: '/pages/login/login'
        });
    },

    guideClose() {
        wx.setStorageSync('guide-finish', 1);
    },

    // 退出登陆
    handleLogout() {
        Dialog.confirm(dialogDefaultConfig(this, '提示', '是否退出登陆'))
            .then(() => {
                this.logout();
            })
            .catch(() => {});
    },

    // 显示编辑用户名弹窗
    handleEditUsername() {
        this.setData({
            newUsername: '',
            usernameDialogVisible: true
        });
    },

    // 显示修改用户密码弹窗
    handleEditPassword() {
        this.setData({
            newPassword: '',
            passwordDialogVisible: true
        });
    },

    // 确认修改用户名
    async confirmEditUsername() {
        if (this.data.newUsername.length === 0) {
            Message.warning(messageDefaultConfig('请输入内容'));
            return;
        }
        if (this.data.newUsername === this.getUserInfo().userName) {
            Message.warning(messageDefaultConfig('新昵称不能与原昵称相同'));
            return;
        }
        try {
            const data = {
                id: this.data.userInfo.id,
                userName: this.data.newUsername
            };
            await updateUser(data);
            // 全局状态管理修改用户名
            this.updateUserInfo('userName', this.data.newUsername);
            Message.success(messageDefaultConfig('修改成功'));
            // 关闭弹窗
            this.closeDialog();
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    async confirmEditPassword() {
        if (!passwordPattern.test(this.data.newPassword)) {
            Message.warning(messageDefaultConfig('密码长度至少8位，使用字母数字组合'));
            return;
        }
        try {
            const data = {
                id: this.data.userInfo.id,
                password: this.data.newPassword
            };
            await updateUser(data);
            this.closeDialog();
            // 修改密码成功后需要重新登陆
            Dialog.confirm(
                Object.assign(dialogDefaultConfig(this, '重新登陆', '修改密码成功，请重新登陆'), {
                    cancelBtn: undefined
                })
            ).then(() => {
                this.logout();
            });
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    // 关闭弹窗
    closeDialog() {
        this.setData({
            usernameDialogVisible: false,
            passwordDialogVisible: false,
            emailDialogVisible: false
        });
    },

    async handleUploadAvatar() {
        try {
            const res = await wx.chooseMedia({
                count: 1,
                mediaType: ['image'],
                sizeType: ['compressed']
            });
            const file = res.tempFiles[0];
            if (file.fileType !== 'image') {
                Message.warning(messageDefaultConfig('请上传图片'));
                return;
            }
            if (file.size > 2 * 1024 * 1024) {
                Message.warning(messageDefaultConfig('头像大小不超过2MB'));
                return;
            }
            const newUrl = await updateUseravatar({ userId: this.data.userInfo.id }, file.tempFilePath);
            this.updateUserInfo('avatar', newUrl);
            Message.success(messageDefaultConfig('修改成功'));
            this.closeDialog();
        } catch (err) {
            if (err.errMsg === 'chooseMedia:fail cancel') {
                Message.warning(messageDefaultConfig('取消选择'));
            } else {
                Message.error(messageDefaultConfig(err.errMsg ?? err));
            }
        }
    },

    handleChangeEmail() {
        this.setData({
            newEmail: '',
            validateCode: '',
            emailDialogVisible: true
        });
    },

    // 确认换绑邮箱
    async confirmChangeEmail() {
        if (!validateChecked) {
            Message.warning(messageDefaultConfig('请完成邮箱校验'));
            return;
        }
        if (!/\d{4}/.test(this.data.validateCode)) {
            Message.warning(messageDefaultConfig('请输入4位数字验证码'));
            return;
        }
        try {
            // 验证邮箱验证码正确性
            await checkValidateCode(this.data.newEmail, this.data.validateCode);
            // 修改账号邮箱
            const data = {
                id: this.data.userInfo.id,
                email: this.data.newEmail
            };
            await updateUser(data);
            validateChecked = false;
            this.closeDialog();
            this.updateUserInfo('email', this.data.newEmail);
            Message.success(messageDefaultConfig('换绑邮箱成功'));
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    // 获取邮箱验证码
    async getValidateCode() {
        if (!emailPattern.test(this.data.newEmail)) {
            Message.error(messageDefaultConfig('请输入正确格式的邮箱地址'));
            return;
        }
        if (this.data.currentSecond !== 0) {
            return;
        }
        try {
            await getValidateCode(this.data.newEmail);
            // 设置获取倒计时
            this.setNewInterval(60);
            validateChecked = true;
            Message.success(messageDefaultConfig('验证码已发送, 请注意查看邮箱'));
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    }
});
